﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
//using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace SS.Client
{
    public class SerializationHelpers
    {
        #region 将对像序列化为二进制
        public static byte[] ObjectToByte(object obj) //obj 可以是数组
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();//此种情况下,mem_stream的缓冲区大小是可变的

            formatter.Serialize(memoryStream, obj);

            byte[] buff = memoryStream.ToArray();
            memoryStream.Close();

            return buff;
        }
        #endregion

        #region 反序列化将二进制为对像
        public static object ByteToObject(byte[] buff, int index, int count)
        {
            IFormatter formatter = new BinaryFormatter();

            MemoryStream stream = new MemoryStream(buff, index, count);
            object obj = formatter.Deserialize(stream);
            stream.Close();

            return obj;
        }
        #endregion
    }
}
